import 'dart:async';
import 'dart:io';
import 'dart:isolate';
import 'dart:ui';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:install_plugin/install_plugin.dart';
import 'package:path_provider/path_provider.dart';
import 'update_widget.dart';

 /// author：lx
 /// date：2021-0126
 /// descr：带进度文字的圆角进度条
class TPUpdteWidget extends StatefulWidget {
 //编译名称
 final String? buildName;
 //编译包名
 final String packageName;
 //编译数量
 final String buildVersionNo;
 //升级版本
 final String buildVersion;
 //升级大小 b
 final double? buildFileSize;
 //升级内容
 final String buildUpdateDescription;
 //升级地址
 final String url;
 //是否强制更新
 bool needForceUpdate;

 /// 标题文字的大小
 final double titleTextSize;
 /// 更新文字内容的大小
 final double contentTextSize;
 /// 按钮文字的大小
 final double buttonTextSize;
 /// 顶部图片
 final Widget? topImage;
 final Widget? closeImage;
 /// 拓展高度(适配顶部图片高度不一致的情况）
 final double extraHeight;
 /// 边框圆角大小
 final double radius;
 /// 主题颜色
 final Color themeColor;
 /// 更新事件
 final VoidCallback? onUpdate;
 /// 可忽略更新
 final bool enableIgnore;
 /// 更新事件
 final VoidCallback? onIgnore;
 /// 进度条的背景颜色
 final Color progressBackgroundColor;
 /// 更新事件
 final VoidCallback? onClose;
 /// 更新按钮内容
 final String updateButtonText;
 /// 忽略按钮内容
 final String ignoreButtonText;
 /// 对话框的宽度
 final double width;
 //开始安装事件
 final VoidCallback startInstallApk;

 TPUpdteWidget(
     {
       Key? key,
       required this.packageName,
       required this.buildVersionNo,
       required this.buildVersion,
       required this.buildUpdateDescription,
       required this.url,
       required this.needForceUpdate,
       required this.startInstallApk,
       this.buildFileSize,
       this.buildName = '',
       this.titleTextSize = 16.0,
       this.contentTextSize = 14.0,
       this.buttonTextSize = 14.0,
       this.progressBackgroundColor = const Color(0xFFFFCDD2),
       this.topImage,
       this.closeImage,
       this.extraHeight = 5.0,
       this.radius = 4.0,
       this.themeColor = Colors.red,
       this.enableIgnore = false,
       this.onIgnore,
       this.updateButtonText = '更新',
       this.ignoreButtonText = '忽略此版本',
       this.onClose,
       this.onUpdate,
       this.width = 0.0,
     }) : super(key: key);
 @override
 _TPUpdteWidgetState createState() => _TPUpdteWidgetState();
}

class _TPUpdteWidgetState extends State<TPUpdteWidget> {
 double progress=0;
 double totalProgress=0;
 bool isTapUpdate=false;

 @override
 void initState() {
   // TODO: implement initState
   super.initState();
 }
 @override
 void dispose() {
   super.dispose();
 }
 _networkInstallApk() async {
   if (progress>=1) {
     print("Wait a moment, downloading");
     return;
   }
   progress = 0;
   print('下载url=${widget.url}');
   var appDocDir = await getTemporaryDirectory();
   String savePath = appDocDir.path + ('/appUpdateDemo'+'/${(widget.buildName??'').isEmpty?'${widget.packageName}':widget.buildName}_${widget.buildVersion}.apk');
   File file =File(savePath);
   if(file.existsSync()){
     print('已经下载完成，删除!');
     await file.delete();
   }
   await Dio().download(widget.url??'', savePath, onReceiveProgress: (count, total) {
     print('download-->count=${count},total=${total},progress=$progress');
     double totalTemp = total*1.0;
     if((widget.buildFileSize??0)>0)totalTemp = (widget.buildFileSize??0);
     final value = count / totalTemp;
     totalProgress = totalTemp*1.0;
     if (progress != value) {
       setState(() {
         if (progress < 1.0) {
           progress = count / totalTemp;
         } else {
           progress = 1.0;
         }
       });
       print((progress * 100).toStringAsFixed(0) + "%");
     }
   });
   if(widget.startInstallApk!=null)widget.startInstallApk();
   final res = await InstallPlugin.install(savePath);
   print("install apk ${res['isSuccess'] == true ? 'success' : 'fail:${res['errorMessage'] ?? ''}'}");
 }

 @override
 Widget build(BuildContext context) {
   return UpdateWidget(
       key: widget.key,
       width: widget.width,
       title: '是否升级到${widget.buildVersion}版本？',
       updateContent: '${widget.buildUpdateDescription}',
       // updateContent: '新版本大小:${(widget.buildFileSize??'0')}M\n${widget.buildUpdateDescription}',
       onUpdate: () => executeDownload(widget.url??''),
       titleTextSize: widget.titleTextSize,
       contentTextSize: widget.contentTextSize,
       buttonTextSize: widget.buttonTextSize,
       progress: progress*1.0,
       totalProgress: totalProgress*1.0,
       progressBackgroundColor: widget.progressBackgroundColor,
       topImage: widget.topImage,
       closeImage: widget.closeImage,
       extraHeight: widget.extraHeight,
       radius: widget.radius,
       themeColor: widget.themeColor,
       enableIgnore: widget.enableIgnore,
       onIgnore: widget.onIgnore,
       isForce: widget.needForceUpdate??false,
       updateButtonText: widget.updateButtonText,
       ignoreButtonText: widget.ignoreButtonText,
       onClose: () => _closeUpdateWidget(),
   );
 }

  executeDownload(String url) async {
    if(widget.needForceUpdate!=null) widget.needForceUpdate = true;
    setState(() {});
    _networkInstallApk();
 }

 _closeUpdateWidget() {
   if(widget.onClose!=null)widget.onClose!();
 }
}
